package com.etalk.crm.controller;

import com.alibaba.fastjson.JSONObject;
import com.etalk.crm.pojo.GradeLevel;
import com.etalk.crm.pojo.Person;
import com.etalk.crm.pojo.StudentDynamics;
import com.etalk.crm.pojo.StudentInfo;
import com.etalk.crm.service.PersonService;
import com.etalk.crm.service.StuDynamicService;
import com.etalk.crm.utils.DateUtil;
import com.etalk.crm.utils.OssGetObject;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static java.util.regex.Pattern.compile;


/**
 * @auther James
 * @date 2019/1/29 10:35
 * @Description
 */
@Controller
@RequestMapping(value = "/stuDynamic",produces = "application/json; charset=utf-8")
public class StudentDynamicCtl {
    private static final Logger logger = LogManager.getLogger(StudentDynamicCtl.class);

    @Resource
    private StuDynamicService stuDynamicService;

    @Resource
    PersonService personService;

    @Value("https://hnres.etalk365.com/")
    String fileUrl;

    /**
     * 动态附件保存路径
     */
    public static final String DYNAMICS_ATTACHMENT_UPLOAD_PATH = "/" +"crm/dynamics" + "/";

    /*
     * @Author James
     * @Description 动态
     * @Date 13:58 2019/1/29
     * @Param
     * @return
     **/
    @RequestMapping(value = "/dynamic")
    public String toDynamic(int personId, String from, Model model, Integer sscCheck) {
        StudentInfo studentInfo = stuDynamicService.selectCcSsc(personId);
        //父级子级 学员属性
//        List<GradeLevel>  selectAllRevisit = stuDynamicService.selectAllRevisit(studentInfo.getState());
//        model.addAttribute("allRevisit",selectAllRevisit);
        model.addAttribute("studentInfo", studentInfo);
        model.addAttribute("personId", personId);
        model.addAttribute("sscCheck", sscCheck);
        model.addAttribute("from", from);
        model.addAttribute("fileUrl", fileUrl);
        return "stuDynamic/stuDynamic";
    }

    @RequestMapping(value = "/selectAllRevisit",method = RequestMethod.POST)
    @ResponseBody
    public String selectAllRevisit(int state,int origianlState,HttpSession session){
        //父级子级 学员属性
        Map<String,Object> jsonMap = new HashMap<>(1);
        List<GradeLevel>  selectAllRevisit = stuDynamicService.selectAllRevisit(state,Integer.parseInt(session.getAttribute("roleId").toString()));
        // 父级之外的标签
        List<GradeLevel>  selectAllExtRevisit = stuDynamicService.selectAllExtRevisit(origianlState,Integer.parseInt(session.getAttribute("roleId").toString()));

        List<GradeLevel> mergedRevisitList = new ArrayList<>();
        mergedRevisitList.addAll(selectAllRevisit);
        mergedRevisitList.addAll(selectAllExtRevisit);
        jsonMap.put("selectAllRevisit",mergedRevisitList);

        return JSONObject.toJSONString(jsonMap);
    }

    /**
     * @Author James
     * @Description 动态分页列表
     * @Date 9:50 2019/1/30
     * @Param
     * @return
     **/
    @RequestMapping(value = "/dynamicPageInfo",method = RequestMethod.POST)
    @ResponseBody
    public String dynamicPageInfo(Integer page,Integer limit,Integer personId,HttpSession session){
        Map<String,Object> jsonMap = new HashMap(3);
        if (page == null) {
            page = 1;
        }
        if (limit == null) {
            limit = 10;
        }
        PageInfo<StudentDynamics> pageInfo = stuDynamicService.selectTrackRemindByBccId(personId,page,limit);
        jsonMap.put("pageInfo",pageInfo);
        jsonMap.put("addUserId",Integer.parseInt(session.getAttribute("userid").toString()));
        return JSONObject.toJSONString(jsonMap);
    }

    /**
     * @Author James
     * @Description 添加动态提醒
     * @Date 13:58 2019/1/29
     * @Param 
     * @return 
     **/
    @RequestMapping(value = "/addDynamic",method = RequestMethod.POST)
    @ResponseBody
    public String addDynamic(@RequestBody StudentDynamics parameter, HttpSession session){
        Map<String,Object> jsonMap = new HashMap<>(5);
        if(parameter.getRemindTime() != null && DateUtil.addTimeToMin(parameter.getRemindTime(), 10).getTime()
                < DateUtil.getCurrentDatetime().getTime()){
            //设置的提醒时间不能小于当前时间后的10分钟
            jsonMap.put("isSuccess",-2);
            return JSONObject.toJSONString(jsonMap);
        }
        if (null != parameter.getSscCCId() && parameter.getSscCCId() > 0 && parameter.getRemindTime()==null) {
            jsonMap.put("isSuccess",-3);
            return JSONObject.toJSONString(jsonMap);
        }
        StudentDynamics studentDynamics = new StudentDynamics();
        studentDynamics.setAddUser(session.getAttribute("loginname").toString());
        studentDynamics.setAddUserId(Integer.parseInt(session.getAttribute("userid").toString()));
        studentDynamics.setAddTime(new Date());
        studentDynamics.setPersonId(parameter.getPersonId());
        studentDynamics.setStudentLogin(parameter.getStudentLogin());
        studentDynamics.setRemindId(parameter.getRemindId());
        studentDynamics.setContent(StringEscapeUtils.unescapeHtml(parameter.getContent()).replaceAll("\n","<br/>"));
        if(parameter.getQuestionnaireId() == null){
            studentDynamics.setQuestionnaireId(0);
        }

        if (StringUtil.isNotEmpty(parameter.getSscCheck())) {
            Person person = new Person();
            person.setId(parameter.getPersonId());
            String con = studentDynamics.getContent();
            if ("1".equals(parameter.getSscCheck())) {
                studentDynamics.setContent("【未正常上课动态】" + con);
                person.setCheckLessonsUptime(new Date());
                jsonMap.put("sign", 1);
                stuDynamicService.updateLessonsUptime(person);
            } else if("2".equals(parameter.getSscCheck())){
                studentDynamics.setContent("【未约课次数达到五次以上】" + con);
                person.setLessonsInactiveUptime(new Date());
                jsonMap.put("sign", 2);
                stuDynamicService.updateLessonsUptime(person);
            }
        }

        //默认为用户
        int sscCCId = Integer.parseInt(session.getAttribute("userid").toString());
        if (null != parameter.getSscCCId() && parameter.getSscCCId() > 0) {
            sscCCId = parameter.getSscCCId();
        }
        int num = stuDynamicService.addStudentDynamics(studentDynamics, parameter.getState(),  parameter.getRemindTime(), Integer.parseInt(session.getAttribute("userid").toString()), sscCCId);
        if (num > 0) {
            if (parameter.getAttachmentPreviewId() != null && parameter.getAttachmentPreviewId().size()>0
                    && parameter.getAttachmentUrl() != null && parameter.getAttachmentUrl().size() >0) {
                //保存附件信息
                stuDynamicService.insertInfoDynamicsAttachments(parameter.getAttachmentPreviewId(), parameter.getAttachmentUrl(), studentDynamics.getId());
            }
            //修改用户到店信息
            if (parameter.getClassStores()!=null && parameter.getClassStores()>=0){
                personService.updateClassStoresByPersonId(studentDynamics.getPersonId(),parameter.getClassStores());
            }
        }
        jsonMap.put("isSuccess", num);
        jsonMap.put("addTime", new Date());
        jsonMap.put("dynamicsId", studentDynamics.getId());
        jsonMap.put("addUserId",Integer.parseInt(session.getAttribute("userid").toString()));
        jsonMap.put("sscCCId",sscCCId);
        return JSONObject.toJSONString(jsonMap);
    }

    /**
     * 获取客户属性
     * @param personId 学员id
     * @return 客户属性
     */
    @ResponseBody
    @PostMapping("/getRevisit")
    public String getRevisit(@RequestParam int personId){
        Map<String,Object> map = new HashMap<>(1);
        Map<String,Object> revisitState=personService.searchRevisitByPersonId(personId);
        if (revisitState==null){
            map.put("status",0);
        }else {
            map.put("status",1);
            map.put("data",revisitState);
        }
        return JSONObject.toJSONString(map);
    }

    /*
     * @Author James
     * @Description 撤销学员动态
     * @Date 15:31 2019/1/29
     * @Param
     * @return
     **/
    @RequestMapping(value = "/revokeDynamic",method = RequestMethod.POST)
    @ResponseBody
    public String revokeDynamic(int dynamicsId,int personId){
        Map<String,Object> jsonMap = new HashMap();
        int num = stuDynamicService.deleteDynamics(dynamicsId);
        jsonMap.put("isSuccess", num);
        //回到上条记录的客户属性
        int lastRevisitStatus = stuDynamicService.selectLastRevisitStatus(personId);
        jsonMap.put("lastRevisitStatus", lastRevisitStatus);
        return JSONObject.toJSONString(jsonMap);
    }

     /**
     * @Author James
     * @Description 修改提醒处理结果(完成处理结果)
     * @Date 15:31 2019/1/29
     * @Param
     * @return
     **/
    @RequestMapping(value = "/modifyStudentAttribute",method = RequestMethod.POST)
    @ResponseBody
    public String modifyStudentAttribute(int dynamicsId) {
        Map<String,Object> jsonMap = new HashMap();
        int num  = stuDynamicService.modifyTrackRemindState(dynamicsId, 1);
        jsonMap.put("code",num);
        return JSONObject.toJSONString(jsonMap);
    }

        /**
     * 上传附件
     *
     * @return
     */
    @RequestMapping(value = "/uploadDynamicsAttachment",method = RequestMethod.POST)
    @ResponseBody
    public String uploadDynamicsAttachment(HttpServletRequest request,String previewId) {
        Map<String,Object> jsonMap = new HashMap();
        List<MultipartFile> files =((MultipartHttpServletRequest)request).getFiles("uploadFiles");
        MultipartFile file = null;
        List<Map> fileNameList = new ArrayList<>();
        if (files != null && files.size() >0) {
            for (int i = 0; i < files.size(); i++) {
                file = files.get(i);
                String currentFileName = file.getOriginalFilename();
                String fileExt = currentFileName.substring(currentFileName.lastIndexOf(".") + 1).trim().toLowerCase();
                String[] allowedExt = new String[]{"jpg", "jpeg", "gif", "png", "mp3", "mp4", "doc", "docx", "ppt", "pptx", "xls", "xlsx", "csv", "zip", "rar", "txt", "pdf"};
                List<String> arr = Arrays.asList(allowedExt);
                SimpleDateFormat sdfForFileName = new SimpleDateFormat("yyyyMMddHHmmss");
                String newName = sdfForFileName.format(new Date()) + new Random().nextInt(1000) + "." + fileExt;
                newName = currentFileName.replace("."+fileExt,"") + "_" + new Random().nextInt(1000) + "." + fileExt;
                System.out.println("new file name==>" + newName);
                try {
                    OssGetObject.uploadDynamicsAttachment(file, newName);
                    Map imgMap = new HashMap();
                    imgMap.put("previewId",previewId);
                    imgMap.put("fileName", newName);
                    imgMap.put("img", DYNAMICS_ATTACHMENT_UPLOAD_PATH + newName);
                    fileNameList.add(imgMap);
                } catch (Exception e) {
                    jsonMap.put("msg","上传失败");
                    continue;
                }
            }
        }
        jsonMap.put("imgList", fileNameList);
        return JSONObject.toJSONString(jsonMap);
    }
    
    
    /*
     * @Author James
     * @Description 删除常用老师
     * @Date 16:38 2019/2/13
     * @Param 
     * @return 
     **/
    @RequestMapping(value = "/delTeacher",method = RequestMethod.POST)
    @ResponseBody
    public String delTeacher(int teacherId,int personId){
        int result = stuDynamicService.delTeacher(teacherId,personId);
        Map<String,Object> jsonMap = new HashMap<>(1);
        if(result > 0){
            jsonMap.put("code", 1);
        }else{
            jsonMap.put("code", 0);
        }
        return JSONObject.toJSONString(jsonMap);
    }

    /**
     * 获取该学生当天的提醒数目
     *
     * @return
     */
    @RequestMapping(value = "/getRemindCount",method = RequestMethod.POST)
    @ResponseBody
    public String getRemindCount(String remindTime,HttpSession session) {
        Map<String,Object> jsonMap = new HashMap<>(2);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        int count = stuDynamicService.selectRemindCount(Integer.parseInt(session.getAttribute("userid").toString()), remindTime);
        jsonMap.put("isSuccess", 1);
        jsonMap.put("remindCount", count);
        return JSONObject.toJSONString(jsonMap);
    }

    /**
     *
     * @param filePath 文件路径
     * @return 数据流
     */
    @RequestMapping(value = "/attachments/download", method = { RequestMethod.GET, RequestMethod.POST })
    public ResponseEntity<byte[]> download(@RequestParam(name = "filePath") String filePath) {
        /*Pattern pattern = compile("(textbooks/).*?\\.[a-zA-Z0-9]+$");*/
        /*Pattern pattern = compile(".*?\\.[a-zA-Z]+$");
        Matcher matcher = pattern.matcher(filePath);*/
        HttpHeaders headers = new HttpHeaders();
        //检查文件名中非法字符，只允许是字母、数字和下划线
        if (StringUtils.isNotEmpty(filePath) && filePath.startsWith("https://") && filePath.lastIndexOf(".")>-1) {
            try {
                //4.读取文件的 输入流，以及响应的输出流，并将数据输出给客户端
                URL url = new URL(filePath);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                //设置超时间为3秒
                conn.setConnectTimeout(3 * 1000);
                //防止屏蔽程序抓取而返回403错误
                conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

                //得到输入流
                InputStream in = conn.getInputStream();
                ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
                byte[] buff = new byte[100];
                int rc;
                while ((rc = in.read(buff, 0, 100)) > 0) {
                    swapStream.write(buff, 0, rc);
                }
                byte[] outByte=swapStream.toByteArray();
                if (outByte!=null) {
                    //HttpHeaders headers = new HttpHeaders();
                    headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
                    headers.setContentDisposition(ContentDisposition.parse("attachment;filename=" + filePath.substring(filePath.lastIndexOf("/") + 1)));
                    return new ResponseEntity<>(outByte, headers, HttpStatus.CREATED);
                }else {
                    headers.add("error-code","404");
                    headers.add("error-msg","file does not exist");
                }
            } catch (Exception e) {
                logger.error(e.getMessage(),e);
            }
        }else {
            headers.add("error-code","406");
            headers.add("error-msg","file path error");

        }

        return new ResponseEntity<>(null, headers,HttpStatus.CREATED);
    }
}
